package com.yuand.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuand.entity.SysRole;
import com.yuand.entity.SysUser;
import com.yuand.service.SysRoleService;
import com.yuand.service.SysUserRoleService;
import com.yuand.service.UserService;
import com.yuand.utils.ResponseResult;
import com.yuand.utils.SecurityUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName: SysUserController
 * @Author: yuandong
 * @Date 2022/1/20 14:47
 * 用户Controller
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;


    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/list")
    public ResponseResult list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, SysUser user){
        PageHelper.startPage(pageNum, pageSize);

        List<SysUser> userList = userService.selectUserList(user);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        return  new ResponseResult(0,"操作成功",pageInfo);
    }


    /**
     * 角色--分配用户
     * @return
     */
    @GetMapping("/authuser/allocatedUserList")
    public ResponseResult allocatedUserList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, SysUser user){
        PageHelper.startPage(pageNum, pageSize);

        // 查询角色已授权用户列表
        List<SysUser> userList = userService.selectAllocatedUserList(user);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        return  new ResponseResult(0,"操作成功",pageInfo);
    }


    /**
     * 查询角色未授权用户列表
     * @return
     */
    @GetMapping("/authuser/unAllocatedUserList")
    public ResponseResult unallocatedUserList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, SysUser user){
        PageHelper.startPage(pageNum, pageSize);

        // 查询角色未授权用户列表
        List<SysUser> userList = userService.selectUnAllocatedUserList(user);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        return  new ResponseResult(0,"操作成功",pageInfo);
    }


    /**
     * 批量选择用户授权
     * @param userIds
     * @param roleId
     * @return
     */
    @PostMapping("/authuser/selectAll")
    public ResponseResult selectAll(Long[] userIds, Long roleId){
        this.userService.saveUserRole(userIds,roleId);
        return new ResponseResult(0,"操作成功");
    }


    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody SysUser user){
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword("123"));
        int flag = this.userService.insertUser(user);
        return new ResponseResult(0,"修改成功");
    }

    /**
     * 用户详情
     * @param userId
     * @return
     */
    @GetMapping(value= {"/selectById/","/selectById/{userId}"})
    public ResponseResult selectById(@PathVariable(value="userId", required = false) Long userId){

        List<SysRole> roles = sysRoleService.selectAll();

        Map<String,Object> map = new HashMap<>();
        //排除超管角色
        map.put("roles",SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if(!Objects.isNull(userId)){
            SysUser user = this.userService.selectUserById(userId);
            map.put("user",user);
            //过滤sys_role中的id
            map.put("roleIds", user.getRoleList().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }

        return new ResponseResult(0,map);
    }


    /**
     * 进入分配用户角色的页面
     * @param userId
     * @return
     */
    @GetMapping("/authRole/{userId}")
    public ResponseResult authRole(@PathVariable Long userId){

        //1:根据userId查询对应的用户信息
        SysUser user = this.userService.selectUserById(userId);
        //2:先查询所有的角色列表
        //3:查询user_role表，查看该用户已经有的角色，已有的角色需要在前端显示的时候置为选中状态
        List<SysRole> roles = this.sysRoleService.selectRolesByUserId(userId);

        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("roles",roles);
        return new ResponseResult(0,map);
    }

    /**
     * 分配角色页面进行提交
     * 如果用户没有选择任何角色，这里的roleIds是null
     * @return
     */
    @PostMapping("/updateAuthRole")
    public ResponseResult updateAuthRole(Long userId, Long[] roleIds){
        //用户授权角色
        this.userService.updateUserRole(userId,roleIds);
        return new ResponseResult(0,"操作成功");
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public ResponseResult update(@RequestBody SysUser user){
        this.userService.updateUserById(user);
        return new ResponseResult(0,"修改成功");
    }

    /**
     * 删除用户
     * 删除的时候不能自己删除自己，不能删除超管
     * 使用ArrayUtils.contains(userIds, getUserId())进行判断
     * userIds是用户在前端选择的用户(100,101);getUseId()是当前登录用户；
     * 也即如果用户勾选的用户包含自己本身，则不允许删除
     * @return
     */
    @PreAuthorize("hasAuthority('sys:user:remove')")
    @PostMapping("/del/{userIds}")
    public ResponseResult del(@PathVariable Long[] userIds){
        if(ArrayUtils.contains(userIds,SecurityUtils.getUserId())){
            return new ResponseResult(1,"该用户不能删除");
        }
        int rows = this.userService.delUserByIds(userIds);
        return rows>0 ? new ResponseResult(0,"删除成功"):new ResponseResult(0,"操作失败");
    }

}
